package demo13;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    DatagramSocket socket=null;
    String ip;
    int port;
    UdpEchoClient(String ip,int port) throws SocketException {
        socket=new DatagramSocket();
        this.ip=ip;
        this.port=port;
    }

    public void start() throws IOException {
        Scanner in=new Scanner(System.in);
        while(true) {
            System.out.print("->");
            String request = in.next();
            DatagramPacket packet = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(ip), port);
            socket.send(packet);

            DatagramPacket respondPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(respondPacket);
            String respond = new String(respondPacket.getData(), 0,respondPacket.getLength());
            System.out.println(respond);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
